package liuliu.throughwaring.ui.activity;

import android.app.Dialog;
import android.content.Intent;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import net.tsz.afinal.annotation.view.CodeNote;

import java.util.ArrayList;
import java.util.List;

import liuliu.custom.control.dialog.LLDialog;
import liuliu.custom.control.edittext.ImageEditText;
import liuliu.custom.control.edittext.SpinnerEditText;
import liuliu.custom.control.image.CircleImageView;
import liuliu.custom.control.picker.DatePickerDialog;
import liuliu.custom.control.toolbar.TToolbar;
import liuliu.custom.method.Utils;
import liuliu.throughwaring.R;
import liuliu.throughwaring.adapter.CommonAdapter;
import liuliu.throughwaring.adapter.ViewHolder;
import liuliu.throughwaring.base.BaseActivity;
import liuliu.throughwaring.control.add.police.person.IRegPersonView;
import liuliu.throughwaring.control.add.police.person.RegPersonListener;
import liuliu.throughwaring.model.CodeModel;
import liuliu.throughwaring.model.PersonModel;
import liuliu.throughwaring.model.Key;
import liuliu.throughwaring.model.PersonModel;

/**
 * Created by liuliu on 2015/11/17   10:49
 * 人员查询
 *
 * @author 柳伟杰
 * @Email 1031066280@qq.com
 */
public class PersonSearchActivity extends BaseActivity implements IRegPersonView {
    public static PersonSearchActivity mInstance;
    @CodeNote(id = R.id.person_search_item_main_user_img)
    CircleImageView photo;
    @CodeNote(id = R.id.person_search_person_type_ll, click = "onClick")
    LinearLayout person_type_ll;
    @CodeNote(id = R.id.person_search_exact_search_ll, click = "onClick")
    LinearLayout exact_search_ll;
    @CodeNote(id = R.id.person_search_right_menu_draw)
    DrawerLayout right_menu;
    @CodeNote(id = R.id.person_search_toolbar)
    TToolbar mToolbar;
    @CodeNote(id = R.id.right_menu_toolbar)
    TToolbar mRightToolbar;
    @CodeNote(id = R.id.right_menu_listview)
    ListView mRightMenu;
    List<CodeModel> mCodeList;
    CodeModel mCode;
    @CodeNote(id = R.id.person_search_exact_search_lb)
    TextView exact_search;
    @CodeNote(id = R.id.person_search_person_type_lb)
    TextView person_type;
    String personType = "null";
    /*左划菜单布局*/
    @CodeNote(id = R.id.right_menu_unit_search_ll)
    LinearLayout right_menu_unit;
    @CodeNote(id = R.id.right_menu_person_search_ll)
    LinearLayout right_menu_person;
    @CodeNote(id = R.id.right_menu_police_search_ll)
    LinearLayout right_menu_police;
    DatePickerDialog datePickerDialog;
    @CodeNote(id = R.id.right_menu_person_search_record_date_begin, click = "onClick")
    SpinnerEditText record_date_begin;
    @CodeNote(id = R.id.right_menu_person_search_record_date_end, click = "onClick")
    SpinnerEditText record_date_end;
    @CodeNote(id = R.id.right_menu_person_search_name)
    ImageEditText menu_name;
    @CodeNote(id = R.id.right_menu_person_search_idcard)
    ImageEditText menu_idcard;
    @CodeNote(id = R.id.right_menu_person_search_unit_name)
    ImageEditText menu_unit_name;
    @CodeNote(id = R.id.right_menu_search_button, click = "onClick")
    Button btn_search;
    List<PersonModel> mPersonList;
    PersonModel mPerson;
    @CodeNote(id = R.id.person_search_main_list)
    ListView mListView;
    RegPersonListener mListener;
    Dialog dialog;
    private LLDialog llDialog;
    private CommonAdapter mAdapter;

    //@CodeNote(id=R.id.right_menu_company_name)
    // LinearLayout right_menu_company;
    @Override
    public void initViews() {
        setContentView(R.layout.activity_person_search);
        mInstance = this;
        mListener = new RegPersonListener(this, this);
        initDatas();
        initlist();//加载主页面list
        llDialog = new LLDialog(this);
    }

    //加载数据
    private void initDatas() {
        String[] s = {"不限", "从业人员", "流动人员", "租赁人员"};
        mCodeList = new ArrayList<>();
        mCodeList = finalDb.findAllByWhere(CodeModel.class, "codeName='Code_PersonStatus'");
        CodeModel code = new CodeModel();
        code.setValue("不限");
        code.setName("null");
        mCodeList.add(code);
    }

    @Override
    public void initEvents() {
        mToolbar.setLeftOnClick(new TToolbar.LeftOnClickListener() {
            @Override
            public void leftclick() {
                mInstance.finish();
            }
        });
    }

    private String getCodeCompanyTypeId(String name) {
        for (int i = 0; i < mCodeList.size(); i++) {
            if (name.equals(mCodeList.get(i).getValue())) {
                return mCodeList.get(i).getName();//onjob
            }
        }
        return "";
    }

    private String getCodeyCompanyValue(String value) {
        for (int i = 0; i < mCodeList.size(); i++) {
            if (value.equals(mCodeList.get(i).getName())) {
                return mCodeList.get(i).getValue();//流动人员
            }
        }
        return "";
    }

    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.person_search_exact_search_ll://精确查找
                drawerManager("精确查找");
                mRightToolbar.setLeftOnClick(new TToolbar.LeftOnClickListener() {
                    @Override
                    public void leftclick() {
                        drawerManager("");
                    }
                });
                mRightMenu.setVisibility(View.GONE);
                right_menu_unit.setVisibility(View.GONE);
                right_menu_person.setVisibility(View.VISIBLE);
                right_menu_police.setVisibility(View.GONE);
                break;
            case R.id.person_search_person_type_ll://根据人员类型进行查找
                drawerManager("人员类型");
                mRightMenu.setVisibility(View.VISIBLE);
                right_menu_unit.setVisibility(View.GONE);
                right_menu_person.setVisibility(View.GONE);
                right_menu_police.setVisibility(View.GONE);
                //左划菜单项点击事件
                mRightMenu.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        drawerManager("");//关闭左划菜单
                        String type = mCodeList.get(position).getValue();
                        person_type.setText(type);
                        personType = mCodeList.get(position).getName();
                        mUtils.WriteString(Key.RYCX_PERSON_TYPE, type);//人员类型
                        //刷新list
                        initlist();
                    }
                });
                mRightToolbar.setLeftOnClick(new TToolbar.LeftOnClickListener() {
                    @Override
                    public void leftclick() {
                        drawerManager("");
                    }
                });
                mRightMenu.setAdapter(new CommonAdapter<CodeModel>(mInstance, mCodeList,
                        R.layout.right_menu_item) {
                    @Override
                    public void convert(final ViewHolder holder, final CodeModel model, int position) {
                        holder.setText(R.id.right_menu_title, model.getValue());
                    }
                });
                break;
            case R.id.right_menu_person_search_record_date_begin:
                datePickerDialog = new DatePickerDialog(mInstance, "");
                datePickerDialog.datePickerDialog(record_date_begin);
                break;
            case R.id.right_menu_person_search_record_date_end:
                datePickerDialog = new DatePickerDialog(mInstance, "");
                datePickerDialog.datePickerDialog(record_date_end);
                break;
            case R.id.right_menu_search_button://确定查询按钮
                drawerManager("");
                //刷新list
                initlist();
                break;
        }
    }

    /*刷新list*/
    private void initlist() {
        boolean isFirst = true;
        String sql = "1=1 ";
        if (!personType.equals("null")) {
            sql += " and PersonStatus='" + personType + "'";
        }
        if (!menu_name.getText().equals("")) {
            sql += " and PersonName like '%" + menu_name.getText() + "%'";
        }
        if (!menu_idcard.getText().equals("")) {
            sql += " and PersonCardId='" + menu_idcard.getText() + "'";
        }
        if (!menu_unit_name.getText().equals("")) {
            sql += " and PersonComapnyName like '%" + menu_unit_name.getText() + "%'";
        }
        if (!record_date_begin.getCenterText().equals("")) {
            System.out.println(record_date_begin.getCenterText());
            sql += " and PersonCreateTime >='" + Utils.changDatetoGeshi(record_date_begin.getCenterText()) + "'";
        }
        if (!record_date_end.getCenterText().equals("")) {
            sql += " and PersonCreateTime <='" + Utils.changDatetoGeshi(record_date_end.getCenterText()) + "'";
        }
        mPersonList = finalDb.findAllByWhere(PersonModel.class, sql);
        if (mAdapter == null) {
            isFirst = false;
            mAdapter = new CommonAdapter<PersonModel>(mInstance, mPersonList,
                    R.layout.item_main_person_search) {
                @Override
                public void convert(final ViewHolder holder, final PersonModel model, int position) {
                    holder.setText(R.id.person_search_item_main_user_name, model.getPersonName());
                    holder.setText(R.id.person_search_item_main_user_state, getCodeyCompanyValue(model.getPersonStatus()));
                    holder.setText(R.id.person_search_item_main_user_unit, model.getPersonComapnyName());
                    holder.setText(R.id.person_search_item_main_create_time, model.getPersonCreateTime());
                    if (!model.getPersonCardImage().equals("null")) {
                        holder.setImageBitmap(R.id.person_search_item_main_user_img, Utils.getBitmapByte(model.getPersonRealImage()));
                    }
                    if (model.getPersonStatus().equals("LeaveJob")) {
                        holder.setVisible(R.id.person_search_item_main_leave_job, false);
                    } else {
                        holder.setVisible(R.id.person_search_item_main_leave_job, true);
                    }
                    holder.setOnClickListener(R.id.person_search_item_main_leave_job, new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            llDialog.setMiddleMessage("确认要离职？");
                            llDialog.setOnPositiveListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {//通知后台给置顶人员离职
                                    model.setCheckInTime(Utils.getDateString(model.getCheckInTime()));
                                    model.setCheckOutTime(model.getCheckInTime());
                                    model.setPersonStatus("LeaveJob");
                                    mListener.RegPerson(model);
                                    llDialog.dismiss();
                                }
                            });
                            llDialog.setOnNegativeListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    llDialog.cancel();
                                }
                            });
                            llDialog.show();

                        }
                    });
                }
            };
        }
        mListView.setAdapter(mAdapter);
        if (!isFirst) {//判断不是第一次登录的时候可进行刷新
            mAdapter.notifyDataSetChanged();
        }
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
                mUtils.IntentPost(PersonDetailActivity.class, new Utils.putListener() {
                    @Override
                    public void put(Intent intent) {
                        intent.putExtra("personid", mPersonList.get(position).getPersonId());
                    }
                });
            }
        });

    }

    /*开启关闭左划菜单*/
    private void drawerManager(String police) {
        if (right_menu.isDrawerOpen(GravityCompat.END) || police == "") {
            right_menu.closeDrawer(GravityCompat.END);
        } else {
            right_menu.openDrawer(GravityCompat.END);
            mRightToolbar.setCenterTitle(police);
        }
    }

    /**
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (right_menu.isDrawerOpen(GravityCompat.END)) {//划出状态
                right_menu.closeDrawer(GravityCompat.END);
            } else {
                this.finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mUtils.WriteString(Key.RYCX_PERSON_TYPE, "");
        mUtils.WriteString(Key.RYCX_NAME, "");
        mUtils.WriteString(Key.RYCX_IDCARD, "");
        mUtils.WriteString(Key.RYCX_UNITNAME, "");
        mUtils.WriteString(Key.RYCX_DATA_BEGIN, "");
        mUtils.WriteString(Key.RYCX_DATA_END, "");
    }

    @Override
    public void onRegPersonResult(boolean isTrue, String mes) {
        if (dialog != null) {
            dialog.dismiss();
        }
        Utils.ToastShort(PersonSearchActivity.this, mes);
        if (isTrue) {
            initlist();
        }
    }
}
